package com.we.flink.loanidlabelplatform.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;

public class TableOfflineDcRepayMsglabel {
    public static final String KFKTABLE = "fdm.rrd03_offline_dc_repay_msg_label";
    public static final String QUERYSQL =
            "select loan_id, "
                    + "uid, "
                    + "if(product_key is null, '', product_key) as product_key, "
                    + "if(next_due_date is null, '', next_due_date) as next_due_date from "
                    + KFKTABLE;

    public String loan_id;
    public long uid;
    public String product_key;
    public String next_due_date;

    public TableOfflineDcRepayMsglabel() {}

    public TableOfflineDcRepayMsglabel(
            String loan_id, long uid, String product_key, String next_due_date) {
        this.loan_id = loan_id;
        this.uid = uid;
        this.product_key = product_key;
        this.next_due_date = next_due_date;
    }

    public static TableOfflineDcRepayMsglabel init(String loan_id) {
        return new TableOfflineDcRepayMsglabel(loan_id, 0L, "", "");
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableOfflineDcRepayMsglabel.QUERYSQL);
        DataStream<Tuple2<Boolean, TableOfflineDcRepayMsglabel>> inputStream =
                tableEnv.toRetractStream(tableRes, TableOfflineDcRepayMsglabel.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableOfflineDcRepayMsglabel>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableOfflineDcRepayMsglabel> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableOfflineDcRepayMsglabel>, String>() {
                                    @Override
                                    public String getKey(
                                            Tuple2<Boolean, TableOfflineDcRepayMsglabel> value)
                                            throws Exception {
                                        return value.f1.getLoan_id();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableOfflineDcRepayMsglabel>, String>() {
                                    ValueState<TableOfflineDcRepayMsglabel>
                                            offlineDcRepayMsglabelVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        offlineDcRepayMsglabelVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableOfflineDcRepayMsglabel>(
                                                                        "OfflineDcRepayMsglabelVState",
                                                                        TableOfflineDcRepayMsglabel
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableOfflineDcRepayMsglabel> value,
                                            Collector<String> out)
                                            throws Exception {
                                        String loan_id = value.f1.getLoan_id();
                                        String next_due_date = value.f1.getNext_due_date();
                                        String product_key = value.f1.getProduct_key();
                                        long uid = value.f1.getUid();

                                        TableOfflineDcRepayMsglabel tmpState =
                                                offlineDcRepayMsglabelVState.value();
                                        TableOfflineDcRepayMsglabel curState =
                                                tmpState == null
                                                        ? TableOfflineDcRepayMsglabel.init(loan_id)
                                                        : tmpState;

                                        if (curState.getUid() != uid
                                                || !curState.getProduct_key().equals(product_key)
                                                || !curState.getNext_due_date()
                                                        .equals(next_due_date)) {
                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("loan_id", loan_id);
                                            jsonObject.put("uid", uid);
                                            jsonObject.put("product_key", product_key);
                                            jsonObject.put("next_due_date", next_due_date);

                                            out.collect(jsonObject.toString());

                                            curState.uid = uid;
                                            curState.product_key = product_key;
                                            curState.next_due_date = next_due_date;
                                            offlineDcRepayMsglabelVState.update(curState);
                                        }
                                    }
                                });
        return out;
    }

    public String getLoan_id() {
        return loan_id;
    }

    public long getUid() {
        return uid;
    }

    public String getProduct_key() {
        return product_key;
    }

    public String getNext_due_date() {
        return next_due_date;
    }
}
